﻿using ComponentGIS.Class;
using ComponentGIS.Command;
using ComponentGIS.Tool;
using ComponentGIS.View;
using ESRI.ArcGIS.AnalysisTools;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.Output;
using ESRI.ArcGIS.SystemUI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace ComponentGIS
{
    public partial class FormMain : Form
    {
        #region 字段属性
        string sMapUnits;
        ILayer pLyr;
        IFeatureLayer m_pFeaLyr;
        IEngineEditor m_pEditor;
        CreateFeatureTool m_pCreateFea;
        #endregion

        #region 构造函数
        public FormMain()
        {
            InitializeComponent();
            m_pEditor = new EngineEditorClass();
        }
        #endregion

        #region 响应事件

        private void FormMain_Load(object sender, EventArgs e)
        {
            //添加图标
            IntPtr Hicon = Properties.Resources.GenericGlobeLarge_B_16.GetHicon();
            Icon newIcon = Icon.FromHandle(Hicon);
            this.Icon = newIcon;
        }

        #region 文件管理
        private void menuItemNewMxd_Click(object sender, EventArgs e)
        {
            try
            {
                IMap map = new MapClass();
                axMapControl.Map = map;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void menuItemOpenMxd_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofdOpenMxd = new OpenFileDialog();
                ofdOpenMxd.CheckFileExists = true;
                ofdOpenMxd.Title = "打开地图文档";
                ofdOpenMxd.Filter = "ArcMap文档(*.mxd)|*.mxd;|ArcMap模板(*.mxt)|" +
                    "*.mxt|发布地图文件(*.pmf)|*.pmf|所有地图格式(*.mxd;*.mxt;*.pmf)|*.mxd;*.mxt;*.pmf";
                ofdOpenMxd.Multiselect = false;
                string sRelPath = Application.StartupPath + @"..\..\..\..\Data\Mxd文件";
                string sAbsPath = System.IO.Path.GetFullPath(sRelPath);
                ofdOpenMxd.InitialDirectory = sAbsPath;
                if (ofdOpenMxd.ShowDialog() == DialogResult.OK)
                    axMapControl.LoadMxFile(ofdOpenMxd.FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void menuItemSaveMxd_Click(object sender, EventArgs e)
        {
            try
            {
                string sMxdFileName = axMapControl.DocumentFilename;
                if (sMxdFileName == null || sMxdFileName == string.Empty)
                {
                    string sRelPath = Application.StartupPath + @"..\..\..\..\Data";
                    string sAbsPath = System.IO.Path.GetFullPath(sRelPath);
                    SaveFileDialog pSaveFileDialog = new SaveFileDialog();
                    pSaveFileDialog.Title = "请选择保存路径";
                    pSaveFileDialog.InitialDirectory = sAbsPath;
                    pSaveFileDialog.OverwritePrompt = true;
                    pSaveFileDialog.Filter = "ArcMap文档（*.mxd）|*.mxd|ArcMap模板（*.mxt）|*.mxt";
                    if (pSaveFileDialog.ShowDialog() == DialogResult.OK)
                        sMxdFileName = pSaveFileDialog.FileName;
                    else
                        return;
                }
                IMapDocument pMapDocument = new MapDocumentClass();
                pMapDocument.New(sMxdFileName);
                pMapDocument.ReplaceContents(axMapControl.Map as IMxdContents);
                pMapDocument.Save();
                MessageBox.Show("保存地图文档成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void menuItemSaveAsMxd_Click(object sender, EventArgs e)
        {
            try
            {
                string sRelPath = Application.StartupPath + @"..\..\..\..\Data";
                string sAbsPath = System.IO.Path.GetFullPath(sRelPath);
                SaveFileDialog pSaveFileDialog = new SaveFileDialog();
                pSaveFileDialog.Title = "请选择保存路径";
                pSaveFileDialog.InitialDirectory = sAbsPath;
                pSaveFileDialog.OverwritePrompt = true;
                pSaveFileDialog.Filter = "ArcMap文档（*.mxd）|*.mxd|ArcMap模板（*.mxt）|*.mxt";
                if (pSaveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    IMapDocument pMapDocument = new MapDocumentClass();
                    pMapDocument.New(pSaveFileDialog.FileName);
                    pMapDocument.ReplaceContents(axMapControl.Map as IMxdContents);
                    pMapDocument.Save();
                    MessageBox.Show("保存地图文档成功!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void menuItemAddShp_Click(object sender, EventArgs e)
        {
            try
            {
                string sRelPath = Application.StartupPath + @"..\..\..\..\Data\SHP数据";
                string sAbsPath = System.IO.Path.GetFullPath(sRelPath);
                OpenFileDialog ofdAddShp = new OpenFileDialog();
                ofdAddShp.InitialDirectory = sAbsPath;
                ofdAddShp.Title = "打开Shape文件";
                ofdAddShp.Multiselect = true;
                ofdAddShp.Filter = "Shape文件（*.shp）|*.shp";
                if (ofdAddShp.ShowDialog() == DialogResult.OK)
                {
                    string[] fileName = ofdAddShp.SafeFileNames;//无路径文件名
                    string path = System.IO.Path.GetDirectoryName(ofdAddShp.FileName);//得到文件夹路径
                    for (int i = 0; i < fileName.Length; i++)
                        axMapControl.AddShapeFile(path, fileName[i]);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void menuItemAddRaster_Click(object sender, EventArgs e)
        {
            try
            {
                string sRelPath = Application.StartupPath + @"..\..\..\..\Data\栅格数据";
                string sAbsPath = System.IO.Path.GetFullPath(sRelPath);
                OpenFileDialog ofdAddRaster = new OpenFileDialog();
                ofdAddRaster.InitialDirectory = sAbsPath;
                ofdAddRaster.Title = "加载栅格数据";
                ofdAddRaster.Filter = "栅格文件 (*.*)|*.bmp;*.tif;*.jpg;*.img|(*.bmp)|*.bmp|" +
                    "(*.tif)|*.tif|(*.jpg)|*.jpg|(*.img)|*.img";
                if (ofdAddRaster.ShowDialog() == DialogResult.OK)
                {
                    for (int i = 0; i < ofdAddRaster.FileNames.Length; i++)
                    {
                        IRasterLayer pRasterLayer = new RasterLayerClass();
                        pRasterLayer.CreateFromFilePath(ofdAddRaster.FileNames[i]);
                        axMapControl.AddLayer(pRasterLayer);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void menuItemOpenMdb_Click(object sender, EventArgs e)
        {
            try
            {
                string sRelPath = Application.StartupPath + @"..\..\..\..\Data\个人地理数据库";
                string sAbsPath = System.IO.Path.GetFullPath(sRelPath);
                OpenFileDialog ofdOpenMdb = new OpenFileDialog();
                ofdOpenMdb.InitialDirectory = sAbsPath;
                ofdOpenMdb.Title = "打开mdb个人数据库";
                ofdOpenMdb.Filter = "个人数据库(*.mdb)|*.mdb";
                if (ofdOpenMdb.ShowDialog() == DialogResult.OK)
                {
                    string sDirectory = System.IO.Path.GetDirectoryName(ofdOpenMdb.FileName);
                    IWorkspaceFactory pWorkspaceFactory = new AccessWorkspaceFactory();
                    IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(ofdOpenMdb.FileName, 0);
                    BasicClass.AddLayersFromWorkspace(pWorkspace, axMapControl);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void menuItemOpenGdb_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog fbdOpenGdb = new FolderBrowserDialog();
                if (fbdOpenGdb.ShowDialog() == DialogResult.OK)
                {
                    IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
                    IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(fbdOpenGdb.SelectedPath, 0);
                    BasicClass.AddLayersFromWorkspace(pWorkspace, axMapControl);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void menuItemOutImage_Click(object sender, EventArgs e)
        {
            try
            {
                string sRelPath = Application.StartupPath + @"..\..\..\..\Data";
                string sAbsPath = System.IO.Path.GetFullPath(sRelPath);
                SaveFileDialog sfdOutPicture = new SaveFileDialog();
                sfdOutPicture.Title = "导出图片";
                sfdOutPicture.InitialDirectory = sAbsPath;
                sfdOutPicture.Filter = "JPGE 文件(*.jpg)|*.jpg|TIF 文件(*.tif)|*.tif|PNG 文件(*.png)|*.png";
                if (sfdOutPicture.ShowDialog() != DialogResult.OK)
                    return;
                IExport pExport = null;
                if (sfdOutPicture.FileName.EndsWith(".jpg"))
                    pExport = new ExportJPEGClass();
                else if (sfdOutPicture.FileName.EndsWith(".png"))
                    pExport = new ExportPNGClass();
                else
                    pExport = new ExportTIFFClass();
                pExport.ExportFileName = sfdOutPicture.FileName;
                pExport.Resolution = axMapControl.ActiveView.ScreenDisplay.
                  DisplayTransformation.Resolution;//分辨率
                tagRECT rect = axMapControl.ActiveView.ExportFrame;//矩形范围
                IEnvelope pEnv = new EnvelopeClass();
                pEnv.PutCoords(rect.left, rect.bottom, rect.right, rect.top);
                pExport.PixelBounds = pEnv;
                axMapControl.ActiveView.Output(pExport.StartExporting(),
                    (int)pExport.Resolution, ref rect,
                    axMapControl.ActiveView.Extent, null);
                pExport.FinishExporting();
                MessageBox.Show("已完成地图导出", "提示");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 地图浏览
        //指针
        private void btnPointerDefault_Click(object sender, EventArgs e)
        {
            axMapControl.CurrentTool = null;
            axMapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;

        }
        //平移
        private void btnPointerPan_Click(object sender, EventArgs e)
        {
            axMapControl.MousePointer = esriControlsMousePointer.esriPointerPan;
        }
        //全图
        private void btnFullExtent_Click(object sender, EventArgs e)
        {
            axMapControl.Extent = axMapControl.FullExtent;
        }
        //放大
        private void btnMapZoomIn_Click(object sender, EventArgs e)
        {
            ICommand cmd = new MapZoomInTool();
            cmd.OnCreate(axMapControl.Object);
            axMapControl.CurrentTool = cmd as ITool;
        }
        //缩小
        private void btnMapZoomOut_Click(object sender, EventArgs e)
        {
            axMapControl.CurrentTool = null;
            ICommand tool = new MapZoomOutTool();
            tool.OnCreate(axMapControl.Object);
            axMapControl.CurrentTool = tool as ITool;
        }
        //前一视图
        private void btnExtentBack_Click(object sender, EventArgs e)
        {
            ICommand cmd = new ExtentBackCommand();
            cmd.OnCreate(axMapControl.Object);
            cmd.OnClick();
        }
        //后一视图
        private void btnExtentForward_Click(object sender, EventArgs e)
        {
            ICommand cmd = new ExtentForwardCommand();
            cmd.OnCreate(axMapControl.Object);
            cmd.OnClick();
        }
        //属性表
        private void btnOpenAttributeTable_Click(object sender, EventArgs e)
        {
            FormAttributeTable frmAttributeTable = new FormAttributeTable((IMapControl2)axMapControl.Object);
            frmAttributeTable.Show();
        }
        //创建书签
        private void btnCreateBookmark_Click(object sender, EventArgs e)
        {
            ICommand cmd = new ControlsMapCreateBookmarkCommandClass();
            cmd.OnCreate(axMapControl.Object);
            cmd.OnClick();
        }
        //管理书签
        private void btnManageBookmark_Click(object sender, EventArgs e)
        {
            ICommand cmd = new ControlsMapManageBookmarksCommandClass();
            cmd.OnCreate(axMapControl.Object);
            cmd.OnClick();
        }
        //自定义比例尺
        private void menuCboMapScale_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)    //Enter
            {
                bool isColon = menuCboMapScale.Text.Contains(":");
                if (isColon)
                {
                    string[] strArray = menuCboMapScale.Text.Split(':');
                    axMapControl.MapScale = double.Parse(strArray[1]);
                }
                else
                    axMapControl.MapScale = double.Parse(menuCboMapScale.Text);
                axMapControl.Refresh();
            }
        }
        //国标比例尺
        private void menuCboMapScale_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sMapScale = menuCboMapScale.SelectedItem.ToString();
            string[] sArray = sMapScale.Split(':');//冒号分隔
            axMapControl.MapScale = double.Parse(sArray[1].Trim(','));//去除逗号
            axMapControl.Refresh();
        }
        #endregion

        #region 选择查询
        //选择要素
        private void btnSelectFeature_Click(object sender, EventArgs e)
        {
            //初始化指针
            axMapControl.CurrentTool = null;
            axMapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
            //选择工具
            ControlsSelectFeaturesTool pTool = new ControlsSelectFeaturesToolClass();
            pTool.OnCreate(axMapControl.Object);
            axMapControl.CurrentTool = pTool as ITool;
        }
        //清空选择
        private void btnClearSelection_Click(object sender, EventArgs e)
        {
            //初始化指针
            axMapControl.Map.ClearSelection();
            axMapControl.Refresh();
        }
        //定位选择
        private void btnZoomToSelection_Click(object sender, EventArgs e)
        {
            if (axMapControl.Map.SelectionCount == 0)
            {
                MessageBox.Show("请先选择要素！", "提示");
            }
            else
            {
                ISelection pSelection = axMapControl.Map.FeatureSelection;
                IEnumFeature pEnumFea = pSelection as IEnumFeature;
                pEnumFea.Reset();
                IFeature pFea = pEnumFea.Next();
                IEnvelope pEnv = new EnvelopeClass();
                while (pFea != null)
                {
                    pEnv.Union(pFea.Extent);
                    pFea = pEnumFea.Next();
                }
                axMapControl.Extent = pEnv;
                axMapControl.Refresh();
            }
        }
        //属性查询
        private void btnQueryByAttribute_Click(object sender, EventArgs e)
        {
            FormQueryByAttribute formQueryByAttribute =
                new FormQueryByAttribute(axMapControl.Object as IMapControl2);
            formQueryByAttribute.ShowDialog();
        }
        //空间查询
        private void btnQueryBySpatial_Click(object sender, EventArgs e)
        {
            FormQueryBySpatial frmQueryBySpatial =
                new FormQueryBySpatial(axMapControl.Object as IMapControl2);
            frmQueryBySpatial.ShowDialog();
        }
        //选择集
        private void btnSelectionSet_Click(object sender, EventArgs e)
        {
            if (axMapControl.Map.SelectionCount != 0)
            {
                FormAttributeTable frmAttributeTable = new FormAttributeTable((IMapControl2)axMapControl.Object, true);
                frmAttributeTable.Show();
            }
            else
                MessageBox.Show("请先选择要素！");
        }
        //识别
        private void btnIdentify_Click(object sender, EventArgs e)
        {
            //初始化指针
            axMapControl.CurrentTool = null;
            axMapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
            //识别对象
            ControlsMapIdentifyTool mapIdentifyTool = new ControlsMapIdentifyToolClass();
            mapIdentifyTool.OnCreate(axMapControl.Object);
            axMapControl.CurrentTool = mapIdentifyTool as ITool;
        }
        //量算
        private void btnMeasure_Click(object sender, EventArgs e)
        {
            //初始化指针
            axMapControl.CurrentTool = null;
            axMapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
            //测量工具
            ControlsMapMeasureTool tool = new ControlsMapMeasureToolClass();
            tool.OnCreate(axMapControl.Object);
            axMapControl.CurrentTool = tool as ITool;
        }
        #endregion

        #region 空间编辑
        //开始编辑
        private void btnStartEditing_Click(object sender, EventArgs e)
        {
            #region 组件库--不推荐
            //ICommand cmd = new ControlsEditingStartCommandClass();
            //cmd.OnCreate(axMapControl.Object);
            //cmd.OnClick(); 
            #endregion

            //1 获取目标图层
            cboEditingLyr.Items.Clear();
            List<string> targetEditingLyr = BasicClass.GetFeatureLayerNameList(axMapControl.Map);
            cboEditingLyr.Items.AddRange(targetEditingLyr.ToArray());
            cboEditingLyr.SelectedIndex = 0;
            //2 获取工作空间&开始编辑
            IDataset pSet = (IDataset)m_pFeaLyr.FeatureClass;
            IWorkspace pWs = pSet.Workspace;
            m_pEditor.EnableUndoRedo(true);//开启撤销重做
            m_pEditor.StartEditing(pWs, axMapControl.Map);
            //3 激活相关控件
            ChangeEditControlsState(true);
        }
        //保存编辑
        private void btnSaveEditing_Click(object sender, EventArgs e)
        {
            #region 组件库--不推荐
            //ICommand cmd = new ControlsEditingSaveCommandClass();
            //cmd.OnCreate(axMapControl.Object);
            //cmd.OnClick();
            #endregion

            try
            {
                DialogResult isSave = MessageBox.Show("是否保存编辑？", "提示",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                IWorkspace pWs = m_pEditor.EditWorkspace;
                if (isSave == DialogResult.Yes)
                {
                    m_pEditor.StopEditing(true);
                    m_pEditor.StartEditing(pWs, axMapControl.Map);
                    axMapControl.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //停止编辑
        private void btnEditingStop_Click(object sender, EventArgs e)
        {
            #region 组件库--不推荐
            //ICommand cmd = new ControlsEditingStopCommandClass();
            //cmd.OnCreate(axMapControl.Object);
            //cmd.OnClick();
            #endregion

            //1 停止编辑
            DialogResult isSave = MessageBox.Show("是否保存编辑？", "提示",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (isSave == DialogResult.Yes)
                m_pEditor.StopEditing(true);
            else
                m_pEditor.StopEditing(false);
            //2 关闭相关控件
            ChangeEditControlsState(false);
            //3 清空&刷新
            axMapControl.CurrentTool = null;
            m_pCreateFea = null;
            axMapControl.Refresh();
        }
        //撤销
        private void btnUndo_Click(object sender, EventArgs e)
        {
            string currentTaskName = m_pEditor.CurrentTask.UniqueName;
            if (m_pCreateFea != null && m_pCreateFea.IsFinishedSketch == false)
                m_pCreateFea.Undo();

        }
        //重做
        private void btnRedo_Click(object sender, EventArgs e)
        {
            if (m_pCreateFea != null && m_pCreateFea.IsFinishedSketch == false)
                m_pCreateFea.Redo();
        }
        //编辑图层
        private void cboEditingLyr_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sFeaLyrName = cboEditingLyr.SelectedItem.ToString();
            m_pFeaLyr = BasicClass.GetFeatureLayer(axMapControl.Map, sFeaLyrName);
            CreateFeatureTool.FeatureLayer = m_pFeaLyr;
            if (m_pCreateFea != null)
                m_pCreateFea.ChangeTargetLyr();
        }
        //创建要素
        private void btnEditingSketch_Click(object sender, EventArgs e)
        {
            #region 组件库--不推荐
            //ICommand cmd = new ControlsEditingSketchToolClass();
            //cmd.OnCreate(axMapControl.Object);
            //axMapControl.CurrentTool = (ITool)cmd; 
            #endregion

            m_pCreateFea = new CreateFeatureTool();
            m_pCreateFea.OnCreate(axMapControl.Object);
            axMapControl.CurrentTool = m_pCreateFea;
            m_pCreateFea.ChangeTargetLyr();
        }
        //编辑要素
        private void btnEditor_Click(object sender, EventArgs e)
        {
            ICommand cmd = new ControlsEditingEditToolClass();
            cmd.OnCreate(axMapControl.Object);
            cmd.OnClick();
            axMapControl.CurrentTool = (ITool)cmd;
        }
        //添加节点
        private void btnEditingVertexAdd_Click(object sender, EventArgs e)
        {
            ICommand cmd = new AddVertexTool();
            cmd.OnCreate(axMapControl.Object);
            axMapControl.CurrentTool = (ITool)cmd;
        }
        //删除节点
        private void btnEditingVertexDel_Click(object sender, EventArgs e)
        {
            #region 组件库
            //ICommand cmd = new ControlsEditingVertexInsertCommandClass();
            //cmd.OnCreate(axMapControl.Object);
            //cmd.OnClick();
            //axMapControl.CurrentTool = (ITool)cmd; 
            #endregion

            ICommand cmd = new DelVertexTool();
            cmd.OnCreate(axMapControl.Object);
            axMapControl.CurrentTool = (ITool)cmd;
        }
        //属性编辑
        private void btnEditingAttribute_Click(object sender, EventArgs e)
        {
            FormAttributeEdit frmAttributeEdit = new FormAttributeEdit((IMapControl2)axMapControl.Object);
            frmAttributeEdit.ShowDialog();
        }
        
        #endregion

        #region 地图控件
        private void axMapControl_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            if (axMapControl.MousePointer == esriControlsMousePointer.esriPointerPan)
                axMapControl.Pan();
            if (e.button == 2 && m_pCreateFea != null &&
                m_pEditor.EditState == esriEngineEditState.esriEngineStateEditing)
            {
                axMapControl.ContextMenuStrip.Show(Control.MousePosition);
            }
        }

        private void axMapControl_OnAfterScreenDraw(object sender, IMapControlEvents2_OnAfterScreenDrawEvent e)
        {
            //1 激活相关控件
            //1.1 地图浏览
            bool isData = false;//存在数据？
            isData = axMapControl.LayerCount > 0 ? true : false;
            barMapBrowse.Enabled = isData;
            //1.2 选择查询
            barSelect.Enabled = isData;
            //1.3 空间编辑
            barEditor.Enabled = isData;
            //1.4 历史视图
            bool canUndo = axMapControl.ActiveView.ExtentStack.CanUndo();
            btnExtentBack.Enabled = canUndo;
            bool canRedo = axMapControl.ActiveView.ExtentStack.CanRedo();
            btnExtentForward.Enabled = canRedo;
            //1.5 选择集
            bool isSelection = false;
            isSelection = axMapControl.Map.SelectionCount > 0 ? true : false;
            btnClearSelection.Enabled = isSelection;
            btnZoomToSelection.Enabled = isSelection;
            btnSelectionSet.Enabled = isSelection;
            if (m_pEditor.EditState == esriEngineEditState.esriEngineStateEditing)
                btnEditingAttribute.Enabled = isSelection;
            //1.6 要素编辑
            if (m_pCreateFea != null)
            {
                btnUndo.Enabled = m_pCreateFea.CanUndo;
                btnRedo.Enabled = m_pCreateFea.CanRedo;
                undoToolStripMenuItem.Enabled = m_pCreateFea.CanUndo;
                redoToolStripMenuItem.Enabled = m_pCreateFea.CanRedo;
            }
            //1.7 节点编辑
            string sTaskName = m_pEditor.CurrentTask.UniqueName;
            bool isModify = sTaskName.Equals("ControlToolsEditing_ModifyFeatureTask");
            btnEditingVertexAdd.Enabled = isModify;
            btnEditingVertexDel.Enabled = isModify;
            //2 视图同步
            IActiveView pActiveView = (IActiveView)axPageLayoutControl.ActiveView.FocusMap;
            IDisplayTransformation displayTransformation = pActiveView.ScreenDisplay.DisplayTransformation;
            displayTransformation.VisibleBounds = axMapControl.Extent;
            IObjectCopy pObjectCopy = new ObjectCopyClass();
            object copyMap = pObjectCopy.Copy(axMapControl.Map);//复制地图到copiedMap中
            object copyToMap = axPageLayoutControl.ActiveView.FocusMap;
            pObjectCopy.Overwrite(copyMap, ref copyToMap); //复制地图
            //3 比例尺
            menuCboMapScale.Text = string.Format("1:{0:#}", axMapControl.MapScale);
        }
        //鼠标坐标
        private void axMapControl_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            sMapUnits = BasicClass.GetMapUnit(axMapControl.Map.MapUnits);
            statusBarLblCoor.Text = string.Format("{0:#.###} {1:#.###} {2}", e.mapX, e.mapY, sMapUnits);
        }
        //快捷键
        private void axMapControl_OnKeyDown(object sender, IMapControlEvents2_OnKeyDownEvent e)
        {
            if (e.keyCode == 27)//Esc
            {
                axMapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
                axMapControl.CurrentTool = null;
            }
        }
        //撤销(右键菜单)
        private void undoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_pCreateFea != null && m_pCreateFea.IsFinishedSketch == false)
                m_pCreateFea.Undo();
        }
        //重做(右键菜单)
        private void redoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_pCreateFea != null && m_pCreateFea.IsFinishedSketch == false)
                m_pCreateFea.Redo();
        }
        //完成草图(右键菜单)
        private void FinishSketchContextMenuItem_Click(object sender, EventArgs e)
        {
            if (m_pCreateFea != null)
                m_pCreateFea.EditSketch.FinishSketch();
        }
        #endregion

        #region 图层管理
        private void axTOCControl_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
        {
            if (e.button == 2)//右键
            {
                esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;
                IBasicMap pBasicMap = null;
                object unk = null;
                object data = null;
                axTOCControl.HitTest(e.x, e.y, ref item, ref pBasicMap, ref pLyr, ref unk, ref data);
                if (item == esriTOCControlItem.esriTOCControlItemLayer)
                {
                    if (pLyr is IFeatureLayer)  //矢量图层
                    {
                        m_pFeaLyr = pLyr as IFeatureLayer;
                        btnAttributeTable.Visible = true;
                        btnLayerSelected.Visible = true;
                        btnLayerSelectable.Visible = true;
                        btnLayerUnSelectable.Visible = true;
                        btnLayerOutput.Visible = true;
                        btnLayerSelectable.Enabled = !m_pFeaLyr.Selectable;
                        btnLayerUnSelectable.Enabled = m_pFeaLyr.Selectable;
                        btnLayerSelected.Enabled = m_pFeaLyr.Selectable;
                    }
                    else  //栅格图层
                    {
                        btnAttributeTable.Visible = false;
                        btnLayerSelected.Visible = false;
                        btnLayerSelectable.Visible = false;
                        btnLayerUnSelectable.Visible = false;
                        btnLayerOutput.Visible = false;
                    }
                    axTOCControl.ContextMenuStrip.Show(Control.MousePosition);
                }
            }
        }
        //属性表
        private void btnAttributeTable_Click(object sender, EventArgs e)
        {
            FormAttributeTable frmAttributeTable = new FormAttributeTable((IMapControl2)axMapControl.Object, m_pFeaLyr.Name);
            frmAttributeTable.Show();
        }
        //图层选择
        private void btnLayerSelected_Click(object sender, EventArgs e)
        {
            IFeatureSelection pFeatureSelection = pLyr as IFeatureSelection;
            pFeatureSelection.SelectFeatures(null, esriSelectionResultEnum.esriSelectionResultNew, false);
            axMapControl.ActiveView.Refresh();
        }
        //图层定位
        private void btnLayerZoom_Click(object sender, EventArgs e)
        {
            axMapControl.Extent = pLyr.AreaOfInterest;
        }
        //图层移除
        private void btnLayerRemove_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult result = MessageBox.Show("是否删除[" + pLyr.Name + "]图层", "提示",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                    axMapControl.Map.DeleteLayer(pLyr);
                //axMapControl.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        //图层可选
        private void btnLayerSelectable_Click(object sender, EventArgs e)
        {
            m_pFeaLyr.Selectable = true;
            btnLayerSelectable.Enabled = !btnLayerSelectable.Enabled;
        }
        //图层不可选
        private void btnLayerUnSelectable_Click(object sender, EventArgs e)
        {
            m_pFeaLyr.Selectable = false;
            btnLayerUnSelectable.Enabled = !btnLayerUnSelectable.Enabled;
            btnLayerSelected.Enabled = !btnLayerSelected.Enabled;
        }
        //导出图层
        private void btnLayerOutput_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sfdOutShp = new SaveFileDialog();
                if (sfdOutShp.ShowDialog() == DialogResult.OK)
                {
                    this.Cursor = Cursors.WaitCursor;
                    Select pLoad = new Select();
                    pLoad.in_features = m_pFeaLyr.FeatureClass;
                    pLoad.out_feature_class = sfdOutShp.FileName;
                    Geoprocessor GP = new Geoprocessor();
                    GP.Execute(pLoad, null);
                    this.Cursor = Cursors.Default;
                    MessageBox.Show("导出shp已完成。", "提示");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        #endregion
        #endregion

        #region 方法成员
        private void ChangeEditControlsState(bool bEnable)
        {
            btnEditingStart.Enabled = !bEnable;

            btnEditingSave.Enabled = bEnable;
            btnEditingStop.Enabled = bEnable;
            btnEditingSketch.Enabled = bEnable;
            btnEditor.Enabled = bEnable;
            cboEditingLyr.Enabled = bEnable;
            if (!bEnable)
                btnEditingAttribute.Enabled = bEnable;

        }

        #endregion

        private void CADToMDBMenuItem_Click(object sender, EventArgs e)
        {
            FormCADToGeodatabase frmCADToMDB = new FormCADToGeodatabase();
            frmCADToMDB.ShowDialog();
        }
    }
}
